/**
 * 
 */
package mx.netbrain.bean;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;

import javax.faces.context.FacesContext;

import mx.netbrain.dao.TreeDao;
import mx.netbrain.dao.TypeFileDao;
import mx.netbrain.dao.impl.TreeDaoImpl;
import mx.netbrain.dao.impl.TypeFileDaoImpl;
import mx.netbrain.model.Tree;
import mx.netbrain.model.Type;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 * @author julian
 * 
 */
public class ImageBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5073071052275139184L;
	@SuppressWarnings("unused")
	private StreamedContent image;

	public ImageBean() {
	}

	public StreamedContent getImage() throws IOException {
		String param = FacesContext.getCurrentInstance().getExternalContext()
				.getRequestParameterMap().get("image_id");
		if (param == null) {
			File iconFile = new File("/netbrain/icon/folder.png");
			return new DefaultStreamedContent(new FileInputStream(iconFile),
					"image/png");
		} else {
			Tree tree = new Tree();
			TreeDao treeDao = new TreeDaoImpl();
			tree = treeDao.findById(Long.parseLong(param));
			if (tree.getExtension() == null) {
				File iconFile = new File("/netbrain/icon/folder.png");
				return new DefaultStreamedContent(
						new FileInputStream(iconFile), "image/png");
			} else {
				Type type = new Type();
				TypeFileDao typeFileDao = new TypeFileDaoImpl();
				type = typeFileDao.findByExtension(tree.getExtension());
				File iconFile = new File(type.getRute() + type.getName());
				return new DefaultStreamedContent(
						new FileInputStream(iconFile), type.getType());
			}
		}
	}

	public void setImage(StreamedContent image) {
		this.image = image;
	}

}
